package utils

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"net"
	"os"
	"x1aCron/internal/global"
)

var (
	AddTask = "add"
	Remove  = "remove"
	List    = "list"
	Stop    = "stop"
	Status  = "status"
	Support = "support"
)

type Requests struct {
	Requests []Request `json:"requests"`
}

type Request struct {
	TaskType string          `json:"taskType"`
	Data     json.RawMessage `json:"data"`
}

type AddTaskData struct {
	Interval   int64  `json:"interval"`
	ActionType string `json:"actionType"`
	ActionData string `json:"actionData"`
}

type RemoveTaskData struct {
	ID int64 `json:"id"`
}

// func (ad *AddTaskData) ToTask() (task *core.Task, err error) {
// 	if _, ok := core.ActionTypeMap[ad.ActionType]; !ok {
// 		return nil, fmt.Errorf("unsupported action type: %s", ad.ActionType)
// 	} else {
// 		actionFunc := core.ActionTypeMap[ad.ActionType]
// 		task = core.NewTask(
// 			time.Duration(ad.Interval)*time.Second,
// 			func() {
// 				actionFunc(ad.ActionData)
// 			},
// 		)
// 	}
// 	return task, nil
// }

func SendDataAndGetResponses(data []byte) error {

	conn, err := net.Dial("unix", global.SocketPath)
	if err != nil {
		fmt.Println("dial error:", err)
		os.Exit(1)
	}
	defer conn.Close()

	// 发送请求
	fmt.Println("Sending data to Unix socket:", global.SocketPath, string(data))
	_, err = conn.Write(append(data, '\n'))
	if err != nil {
		fmt.Println("write error:", err)
		return err
	}

	// 用 bufio.Reader 按行读取
	fmt.Println("waiting for response...")
	reader := bufio.NewReader(conn)
	line, err := reader.ReadString('\n') // 读到 '\n' 为止
	if err != nil {
		fmt.Println("read error:", err)
		return err
	}

	var pretty bytes.Buffer
	err = json.Indent(&pretty, []byte(line), "", "  ") // 第二个参数是缩进字符串
	if err != nil {
		panic(err)
	}

	fmt.Println(pretty.String())
	return nil
}
